package cn.cyh.order.service.impl;


import cn.cyh.basic.service.impl.BaseServiceImpl;
import cn.cyh.basic.uitls.CodeGenerateUtils;
import cn.cyh.basic.uitls.DistanceUtil;
import cn.cyh.basic.uitls.PageList;
import cn.cyh.basic.uitls.Point;
import cn.cyh.order.constants.OrderConstans;
import cn.cyh.order.domain.AdoptOrder;
import cn.cyh.order.domain.OrderAddress;
import cn.cyh.order.domain.ProductOrder;
import cn.cyh.order.domain.ProductOrderDetail;
import cn.cyh.order.mapper.OrderAddressMapper;
import cn.cyh.order.mapper.ProductOrderDetailMapper;
import cn.cyh.order.mapper.ProductOrderMapper;
import cn.cyh.order.query.ProductOrderQuery;
import cn.cyh.order.service.IProductOrderService;
import cn.cyh.org.domain.Employee;
import cn.cyh.org.domain.Shop;
import cn.cyh.org.mapper.EmployeeMapper;
import cn.cyh.org.mapper.ShopMapper;
import cn.cyh.pay.constants.PayConstants;
import cn.cyh.pay.domain.PayBill;
import cn.cyh.pay.mapper.PayBillMapper;
import cn.cyh.pay.service.IPayBillService;
import cn.cyh.product.domain.Product;
import cn.cyh.product.mapper.ProductMapper;
import cn.cyh.user.domain.LoginInfo;
import cn.cyh.user.domain.User;
import cn.cyh.user.domain.UserAddress;
import cn.cyh.user.mapper.UserAddressMapper;
import cn.cyh.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

@Service
public class ProductOrderServiceImpl extends BaseServiceImpl<ProductOrder> implements IProductOrderService {

    @Autowired
    private ProductOrderMapper productOrderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductOrderDetailMapper productOrderDetailMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IPayBillService payBillService;

    @Override
    @Transactional
    public String submit(Map<String, Object> params, LoginInfo loginInfo) {
        // 校验参数
//                address_id: '1', // 收获地址
//                service_method:'0',
//                pay_method:'2', // 支付方式
//                product_id:null,
//                product_num:'3' // 购买数量
        Long addressId = Long.valueOf(params.get("address_id").toString());
        Integer serviceMethod = Integer.valueOf(params.get("service_method").toString());
        Long payMethod = Long.valueOf(params.get("pay_method").toString());
        Long productId = Long.valueOf(params.get("product_id").toString());
        Integer productNum = Integer.valueOf(params.get("product_num").toString());
        // 分配门店
        // 绑定用户
        Product product = productMapper.loadById(productId);
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());

        UserAddress userAddress = userAddressMapper.loadById(addressId);
        // 初始化服务
        ProductOrder order = initProduct(userAddress, productNum, product, user);
        // 生成统一支付标识
        order.setPaySn(CodeGenerateUtils.generateUnionPaySn());
        productOrderMapper.save(order);
        // 改销量
        long num = product.getSalecount() + productNum;// 购买次数+上总量
        product.setSalecount(num);
        productMapper.update(product);
        // 创建服务订单
        ProductOrderDetail detail = getProductOrderDetail(num, order, product);
        productOrderDetailMapper.save(detail);
        // 订单地址
        OrderAddress orderAddress = userAddress2OrderAddress(order, userAddress);
        orderAddressMapper.save(orderAddress);
        // 支付订单
        PayBill payBill = getPayBill(payMethod, user, order);
        payBillMapper.save(payBill);

        // 统一支付接口
        return payBillService.pay(payBill);
        // 创建超时未支付取消订单
    }

    private OrderAddress userAddress2OrderAddress(ProductOrder order, UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress,orderAddress);
        orderAddress.setId(null);
        orderAddress.setOrder_id(order.getId());
        orderAddress.setOrderSn(order.getOrderSn());
        return orderAddress;
    }

    /**
     * 获取服务订单
     *
     * @param num
     * @param order
     * @param product
     * @return
     */
    private ProductOrderDetail getProductOrderDetail(long num, ProductOrder order, Product product) {
        ProductOrderDetail detail = new ProductOrderDetail();
        BeanUtils.copyProperties(product, detail);
        detail.setId(null);
        detail.setSalecount(num);
        detail.setOrder_id(order.getId());
        return detail;
    }

    /**
     * 初始化服务
     *
     * @param userAddress
     * @param productNum
     * @param product
     * @param user
     * @return
     */
    private ProductOrder initProduct(UserAddress userAddress, Integer productNum, Product product, User user) {
        ProductOrder order = new ProductOrder();
        order.setDigest("[摘要]" + product.getName());
        order.setPrice(product.getSaleprice().multiply(new BigDecimal(productNum)));// 总价格= 价格*数量
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());// 生成唯一订单编号
        order.setOrderSn(orderSn);
        order.setProduct_id(product.getId());
        order.setUser_id(user.getId());
        order.setLastPayTime(new Date(System.currentTimeMillis() + OrderConstans.LSAT_PAY_TIME));
        // 获取最近的店铺
        Point point = DistanceUtil.getPoint(userAddress.getFullAddress());
        if (point != null) {
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopMapper.loadAll());
            order.setShop_id(nearestShop.getId());
        }

        return order;

    }

    @Override
    public void cancelOrder(Long orderId) {

    }

    @Override
    public PageList<ProductOrder> admin(ProductOrderQuery query, LoginInfo loginInfo) {
        Employee employee = employeeMapper.loadByLoginInfoId(loginInfo.getId());
        if (employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    private PayBill getPayBill(Long payMethed, User user, ProductOrder order) {
        PayBill payBill = new PayBill();
        payBill.setDigest(order.getDigest());
        payBill.setMoney(order.getPrice());
        payBill.setUnionPaySn(order.getPaySn());
        payBill.setLastPayTime(new Date(System.currentTimeMillis()+ OrderConstans.LSAT_PAY_TIME));
        payBill.setPayChannel(payMethed);
        payBill.setShop_id(order.getShop_id());
        // 订单类型
        payBill.setBusinessType(PayConstants.BUSINESS_TYPE_PRODUCT);
        payBill.setBusinessKey(order.getId());
        payBill.setUser_id(order.getUser_id());
        payBill.setNickName(user.getUsername());
        return payBill;
    }
}
